/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.pig4cloud.pig.juhe.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGameInfoMapper;
import com.pig4cloud.pig.juhe.admin.service.JuheGameChannelService;
import com.pig4cloud.pig.juhe.api.entity.JuheGameChannel;
import com.pig4cloud.pig.juhe.api.entity.JuheGameInfo;
import com.pig4cloud.pig.juhe.api.entity.JuheOrderInfo;
import com.pig4cloud.pig.juhe.admin.mapper.JuheOrderInfoMapper;
import com.pig4cloud.pig.juhe.admin.service.JuheOrderInfoService;
import com.pig4cloud.pig.juhe.api.util.HttpUtils;
import com.pig4cloud.pig.juhe.api.util.SecurityUtils;
import com.pig4cloud.pig.juhe.api.vo.JuheOrderInfoVo;
import com.sjda.framework.common.utils.DateUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * 聚合订单表
 *
 * @author yuwenfeng
 * @date 2021-09-02 13:56:17
 */
@Service
@AllArgsConstructor
@Slf4j
public class JuheOrderInfoServiceImpl extends ServiceImpl<JuheOrderInfoMapper, JuheOrderInfo> implements JuheOrderInfoService {

	private final JuheGameInfoMapper juheGameInfoMapper;

	private final JuheGameChannelService juheGameChannelService;

	@Override
	public Page<JuheOrderInfoVo> getJuheOrderInfoVoPage(Page<JuheOrderInfo> page, QueryWrapper<JuheOrderInfo> query) {
		return baseMapper.selectJuheOrderInfoVoPage(page, query);
	}

	@Override
	public R compensateOrder(Long orderId) {
		JuheOrderInfo orderInfo = baseMapper.selectOne(new QueryWrapper<JuheOrderInfo>().eq("order_id", orderId).eq("order_status", 2).eq("game_status", 1));
		if (null == orderInfo) {
			return R.failed("当前订单无法补单");
		}
		JuheGameInfo gameInfo = juheGameInfoMapper.selectById(orderInfo.getGameId());
		if (null != gameInfo) {
			Date nowTime = new Date();
			Map<String, String> paramMap = new TreeMap<>();
			paramMap.put("user", orderInfo.getRoleName());
			paramMap.put("jhOpenId", String.valueOf(orderInfo.getOpenId()));
			paramMap.put("orderid", orderInfo.getOrderSerial());
			paramMap.put("gameorder", orderInfo.getGameOrderSerial());
			paramMap.put("productid", orderInfo.getGoodsCode());
			paramMap.put("total", orderInfo.getOrderFee().toString());
			paramMap.put("roleid", orderInfo.getRoleId());
			paramMap.put("serverid", orderInfo.getServerId());
			paramMap.put("time", DateUtils.dateToString(nowTime, DateUtils.YYYYMMDDHHMMSS));
			paramMap.put("extension", orderInfo.getTraInfo());
			paramMap.put("backStatus", "2");
			paramMap.put("jHAppId", gameInfo.getAppId());
			String signature = SecurityUtils.getJhPaySign(paramMap, gameInfo.getAppSecret());
			paramMap.put("sign", signature);

			// 发货地址 - 如果配置了渠道发货地址优先使用， 否则默认使用游戏发货地址
			String payCallbackUrl = gameInfo.getPayNotifyUrl();
			JuheGameChannel juheGameChannel = juheGameChannelService.getOne(Wrappers.<JuheGameChannel>lambdaQuery()
					.eq(JuheGameChannel::getChannelId, orderInfo.getChannelId()).eq(JuheGameChannel::getGameId, orderInfo.getGameId())
					.eq(JuheGameChannel::getDelFlag, 0).last("LIMIT 1"));
			if (null != juheGameChannel && StringUtils.isNotBlank(juheGameChannel.getPayCallbackUrl())){
				payCallbackUrl = juheGameChannel.getPayCallbackUrl();
			}

			log.info("补单发货地址：{}", payCallbackUrl);
			log.info("游戏发货参数：paramMap={}", JSON.toJSONString(paramMap));
			String resultStr = HttpUtils.doPost(payCallbackUrl, paramMap);
			log.info("游戏发货返回值：resultStr={}", resultStr);
			JSONObject resultJson = JSON.parseObject(resultStr);
			if (null != resultJson && ("success".equals(resultJson.getString("status")) || "0".equals(resultJson.getString("code")))) {
				orderInfo.setGameStatus(2);
				orderInfo.setDeliverTime(nowTime);
				baseMapper.updateById(orderInfo);
				return R.ok();
			}
			return R.failed("游戏服务器响应失败:" + resultStr);
		}
		return R.failed("游戏配置错误");
	}
}
